﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace MVC_Project.UI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //设置允许Cors 跨域访问
            //config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            //允许Ajax 跨域访问
            var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethods"];
            var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"];
            var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"];
            var geduCors = new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods)
            {
                SupportsCredentials = true
            };
            config.EnableCors(geduCors);



            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //移除默认返回 XML 格式数据 
            config.Formatters.Remove(config.Formatters.XmlFormatter);


            //全局捕获异常
            //config.Filters.Add(new ApiExceptionAttribute());
        }
    }
}
